package com.xavier.utils;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    /**
     * 加密
     */
    public static String Encrypt(String sSrc, String sKey, String sIv) throws Exception {
        if (sKey == null) {
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            return null;
        }
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(sIv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes());
        byte[] encrypted2 = Base64.encodeBase64(encrypted);
        return new String(encrypted2);
    }

    /**
     * AES解密
     */
    public static String decrypt(String data, String key) throws Exception {
        try {
            byte[] bytes1 = AES_CBC_Decrypt(decryptBASE64(data), key.getBytes("utf-8"), key.substring(0, 16).getBytes());
            return new String(bytes1, "utf-8");
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 解密方法
     */
    public static byte[] AES_CBC_Decrypt(byte[] content, byte[] keyBytes,
                                         byte[] iv) throws Exception {
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
        byte[] result = cipher.doFinal(content);
        return result;
    }

    /**
     * 将base64类型的字符串转成byte类型
     */
    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key.getBytes());
    }

}
